<?php

namespace App\Models\Shop;

use App\Models\User\WxUser;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class WxShopOrder extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'wx_shop_order';

    protected static function boot()
    {
        parent::boot();
        static::created(function ($model) {

        });
    }

    public function user()
    {
        return $this->hasOne(WxUser::class,'id','user_id');
    }

    public function seller()
    {
        return $this->hasOne(WxUser::class,'id','seller_user_id');
    }


    public function goods()
    {
        return $this->hasMany(WxShopOrderGoods::class, 'order_id', 'id');
    }

    public function getUserRemarkAttribute($value)
    {
        if(_empty_($value)){
            return '';
        }
        if($this->order_from == 7){
            return json_decode($value, true);
        }else{
            return $value;
        }
    }

    public function getOrderGoodsIdAttribute($value)
    {
        return array_map(function ($v) {
            return (int)$v;
        }, json_decode(str_replace("'", '"', _empty_default_($value, '[]')), true));
    }

    public function setOrderGoodsIdAttribute($value)
    {
        $this->attributes['order_goods_id'] = $this->processOrderGoodsIdAttribute($value);
    }

    protected function processOrderGoodsIdAttribute($value)
    {
        if (is_array($value) && count($value) > 0) {
            $arr = array_map(function ($v) {
                return (int)$v;
            }, $value);

            $str = "";
            foreach ($arr as $num) {
                $str .= (",'".$num."'");
            }
            return '[' . ltrim($str, ',') . ']';
        }else if(is_string($value) && strpos($value, '[') === 0){
            return $value;
        } else {
            return null;
        }
    }

}
